package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.mapper.ApAssociateWordsMapper;
import com.heima.search.model.Trie;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
@Log4j2
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 联想词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1 检查参数
        if (dto==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查
        if (dto.getPageSize()>50){
            dto.setPageSize(50);
        }
        //2 模糊查询
        IPage page = new Page(0, dto.getPageSize());
        page = page(page, Wrappers.<ApAssociateWords>lambdaQuery()
                .like(ApAssociateWords::getAssociateWords,dto.getSearchWords()));
        return ResponseResult.okResult(page.getRecords());
    }

    /**
     * 查询关键字联想词  v2版本
     * @param dto
     * @return
     */
    @Override
    public ResponseResult searchV2(UserSearchDto userSearchDto) {
        //1 从redis中获取数据
        String associateList = redisTemplate.opsForValue().get("associate_list");
        List<ApAssociateWords> list = null;
        //2 判断数据是否存在，若存在直接返回；不存在，查询数据库，再放入redis中
        if (StringUtils.isNotBlank(associateList)){
            list = JSON.parseArray(associateList,ApAssociateWords.class);
        }else {
            list = list();
            redisTemplate.opsForValue().set("associate_list", JSON.toJSONString(list));
        }
        //3 初始化trie数据结构
        Trie t = new Trie();
        for (ApAssociateWords apAssociateWords : list) {
            t.insert(apAssociateWords.getAssociateWords());
        }
        //4 匹配关键字返回
        List<Map> resultList = new ArrayList<>();
        List<String> associateWordList = t.startWith(userSearchDto.getSearchWords());
        for (String s : associateWordList) {
            Map map = new HashMap();
            map.put("associateWords",s);
            resultList.add(map);
        }
        return ResponseResult.okResult(resultList);
    }
}
